package org.dk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.dk.domain.DataResult;
import org.dk.em.DataResultEnum;
import org.dk.pojo.*;
import org.dk.service.AddressService;
import org.dk.service.OrderService;
import org.dk.service.TbItemService;
import org.dk.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("orderController")
public class OrderController {

    @Reference
    private TbItemService tbItemService;

    @Reference
    private AddressService addressService;

    //导入生成id的工具类
    private IdWorker idWorker = new IdWorker();

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private OrderService orderService;

    @RequestMapping("toOrderInfo")
    public String toOrderInfo(Long[] ids, Model model){
        List<TbItem> tbOrderItems = tbItemService.selectItemid(ids);
        for (TbItem tbOrderItem : tbOrderItems) {
            System.out.println(tbOrderItem.getTitle());
        }
        return "getOrderInfo";
    }

    @RequestMapping("addOrder")
    @ResponseBody
    public DataResult addOrder(Long id){
        //调用工具类生成id
        long sellerOrderId = idWorker.nextId();
        //创建容器,放入id
        Map<String,Object> map = new HashMap<>();
        map.put("sellerOrderId",String.valueOf(sellerOrderId));//订单id
        double priceAll = 0;
        TbAddress address = addressService.selectAddress(id);
        //获取登陆的用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //通过用户把redis中的数据拿出来
        List<Cart> cartList = (List<Cart>)redisTemplate.boundHashOps("carList").get(user.getUsername());
        //两个对象,一个订单一个详情
        List<TbOrder> list = new ArrayList<>();
        List<TbOrderItem> itemList = new ArrayList<>();
        //循环cart
        for (Cart cart : cartList) {
            TbOrder order = new TbOrder();
            long str = idWorker.nextId();
            order.setOrderId(str);
            order.setSellerId(cart.getSellerId());
            order.setPaymentType("1");
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(user.getUsername());
            order.setReceiver(address.getContact());
            order.setReceiverAreaName(address.getAddress());
            order.setSellerorderid(String.valueOf(sellerOrderId));
            order.setReceiverMobile(address.getMobile());
            double price = 0;
            //在循环OrderItemlist获取购物车明细
            for (TbOrderItem orderItem : cart.getOrderItemlist()) {
                orderItem.setSellerId(String.valueOf(sellerOrderId));
                orderItem.setOrderId(str);
                orderItem.setId(idWorker.nextId());
                itemList.add(orderItem);
                price += orderItem.getTotalFee().doubleValue();//金额累计
            }
            order.setPayment(BigDecimal.valueOf(price));
            list.add(order);
            priceAll += price;
            orderService.addOrder(list,itemList);
            map.put("priceAll",priceAll);
            map.put("id",sellerOrderId);
        }

        return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData(map);
    }

    @RequestMapping("toAlipay")
    public String toAlipay(Model model, String sellerOrderId, BigDecimal priceAll){
        model.addAttribute("sellerOrderId",sellerOrderId);
        model.addAttribute("priceAll",priceAll);
        return "alipay";
    }

    @RequestMapping("selectOrder")
    @ResponseBody
    public DataResult selectOrder(){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            List<OrderVo> orderList = orderService.selectOrder(user.getUsername());
            String s = JSONObject.toJSONString(orderList);
            return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData(s);
        }catch (Exception e){
            e.printStackTrace();
            return DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }

    @RequestMapping("deleteOrder")
    @ResponseBody
    public DataResult deleteOrder(String id){
        try {
            System.out.println(Long.valueOf(id));
            TbOrderItem orderItem = orderService.selectOrderId(id);
            TbOrder order = orderService.selectAlipayId(orderItem.getOrderId());
            Map<String,Object> map = new HashMap<>();
            map.put("WIDTQout_trade_no",order.getSellerId());
            map.put("WIDTQtrade_no",order.getAlipayid());
            map.put("WIDTRrefund_amount",orderItem.getTotalFee());
            map.put("WIDTRout_request_no",id);
            return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData(map);
        }catch (Exception e){
            e.printStackTrace();
            return DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }
}
